#!/usr/bin/env python

# This example demonstrates the use of vtkCardinalSpline.
# It creates random points and connects them with a spline
import os, sys
import vtk
import vtktudoss
from wx import *
import wx.lib.stattext
import wx.aui
from vtk.wx.wxVTKRenderWindow import *
from vtk.wx.wxVTKRenderWindowInteractor import *
from vtk.util.colors import tomato, banana
import time


try:
    import extended.Annotation as Annotation
    import extended.WidgetCollection as WidgetCollection
    import extended.WidgetOverlay as WidgetOverlay
    import extended.PlotOverlay as PlotOverlay
    import extended.Plotter as Plotter
    import extended.Scatter as Scatter
    import extended.TimeWindowTrace as TimeWindowTrace
    import extended.GUI_wxglade as GUI_wxglade
except ImportError:
    import Annotation
    import WidgetCollection
    import WidgetOverlay
    import PlotOverlay    
    import Plotter
    import Scatter
    import TimeWindowTrace
    import GUI_wxglade

[wxID_FRAME, wxID_NOTEBOOK2, wxID_SAVE, wxID_QUIT
] = [wx.NewId() for _init_ctrls in range(4)]
    
def create(parent, root):    
    return wxFrame(parent, root)
    
class wxFrame(wx.Frame):
    def _init_ctrls(self):
        dispsize = wx.DisplaySize()        
        wx.Frame.__init__(self, id=wxID_FRAME, name='wxFrame', parent=None,
              pos=wx.Point(0, 0),  size = (dispsize[0], dispsize[1]-100),
              style=wx.DEFAULT_FRAME_STYLE, title=u'PatternViewer')
        
        antialiasing = False
        self.showsliders = False
        showcaption = True
        showtraceroptions = True
        
        mainbackgroundcolor = [0.3, 0.3, 0.3]
        #~ mainbackgroundcolor = [1.0, 1.0, 1.0]
                
        self.cellpicker = vtk.vtkPointPicker()
        self.cellpicker.SetTolerance(0.0025)
        #~ self.cellpicker.InitializePickList()
        #~ self.cellpicker.PickFromListOn()   
        
        color1 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]#
        self.ren1 = vtk.vtkRenderer()
        self.renwini1 = wxVTKRenderWindowInteractor(self, -1)
        self.renwini1.GetRenderWindow().AddRenderer(self.ren1)
        self.interactorstyle1 = vtk.vtkInteractorStyleTrackballCamera()
        self.renwini1.SetInteractorStyle(self.interactorstyle1)        
        self.ren1.SetBackground(mainbackgroundcolor)
        cam1 = self.ren1.GetActiveCamera()
        cam1.SetViewUp(0, 0, 1)
        cam1.SetFocalPoint(13, 14, 12)
        cam1.SetPosition(-100, 20, 25)
        self.ren1.ResetCamera()
        self.renwini1.CreateRepeatingTimer(10)
        if antialiasing:
            self.renwini1.GetRenderWindow().SetAAFrames(12)
        self.timerobserver = self.renwini1.AddObserver("TimerEvent", self.timerCB)
        self.ren1overlay = WidgetOverlay.create(self, self.renwini1, self.ren1)     
        #self.renwini1.AddObserver("LeftButtonPressEvent", self.JointClicked, 0.0)    
        self.renwini1.Unbind(wx.EVT_LEFT_DOWN)
        self.renwini1.Bind(wx.EVT_LEFT_DOWN, self.JointClicked)
        
        color2 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]#
        #~ color2 = [0.0,0.0,0.0]#[0.4,0.4,0.4]
        self.ren2 = vtk.vtkRenderer()
        self.renwini2 = wxVTKRenderWindowInteractor(self, -1)        
        self.renwini2.GetRenderWindow().AddRenderer(self.ren2)
        interactorstyle2 = vtk.vtkInteractorStyleTrackballCamera()          
        self.renwini2.SetInteractorStyle(interactorstyle2)        
        self.ren2.SetBackground(mainbackgroundcolor)
        self.annotation2 = Annotation.create(self, None, self.renwini2.GetRenderWindow(), self.ren2)
        currentcam = self.ren2.GetActiveCamera()
        currentcam.SetPosition(152, 43, -38)
        currentcam.SetClippingRange(40, 322)
        currentcam.SetViewUp(-0.34, 0.93, 0.027)
        currentcam.SetFocalPoint(0.614, -14.8, 36.8)        
        
        interactionobserver2 = interactorstyle2.AddObserver("InteractionEvent",self.UpdateRenderer2)     
        
        color3 = [0.0, 0.0, 0.0] # [0.5,0.5,0.5]#
        self.ren3 = vtk.vtkRenderer()
        self.renwini3 = wxVTKRenderWindowInteractor(self, -1)        
        self.renwini3.GetRenderWindow().AddRenderer(self.ren3)
        interactorstyle3 = vtk.vtkInteractorStyleImage()  
        self.renwini3.SetInteractorStyle(interactorstyle3)        
        self.ren3.SetBackground(mainbackgroundcolor)
        cam1 = self.ren3.GetActiveCamera()
        cam1.SetViewUp(0, 1, 0)
        cam1.SetFocalPoint(4.75, -1.0, 0)
        cam1.SetPosition(4.75, -1.0, 4)#5.5, -0.5, 4)
        cam1.ParallelProjectionOn ()
        self.ren3.ResetCamera()
        if antialiasing:
            self.renwini3.GetRenderWindow().SetAAFrames(12)
        self.ren3overlay = PlotOverlay.create(self, self.renwini3, self.ren3)     
        
        interactionobserver3 = interactorstyle3.AddObserver("InteractionEvent",self.UpdateRenderer3)
        

        #1680
        self.mgr = wx.aui.AuiManager(self)
        leftpanel = wx.Panel(self, -1, size = (0, 0))
        self.paneInfo1 = wx.aui.AuiPaneInfo()        
        self.paneInfo1.Bottom().Layer(0) #1
        self.paneInfo1.Row(200)        
        self.paneInfo1.BestSize([dispsize[0] - 200, 300])
        self.paneInfo1.MinSize([200, 50])
        self.paneInfo1.CaptionVisible(showcaption)
        
        self.paneInfo2 = wx.aui.AuiPaneInfo()
        self.paneInfo2.Left().Layer(1  ) #2
        #~ self.paneInfo2.Position(0)
        self.paneInfo2.Row(0)
        self.paneInfo2.Resizable(False)
        #~ self.paneInfo2.MinSize([200, 300])
        #~ self.paneInfo2.BestSize([200, 300])
        self.paneInfo2.CaptionVisible(showcaption)
        
        self.paneInfo3 = wx.aui.AuiPaneInfo()
        self.paneInfo3.Center().Layer(2) #0
        #~ self.paneInfo3.Position(0)
        self.paneInfo3.Row(1)
        self.paneInfo3.MinSize([50, 50])
        self.paneInfo3.BestSize([700, 400])
        #~ self.paneInfo3.BestSize([int((dispsize[0] - 200)/2), 200])
        self.paneInfo3.CaptionVisible(showcaption)
        
        self.paneInfo4 = wx.aui.AuiPaneInfo()
        self.paneInfo4.Right().Layer(0) #0
        #~ self.paneInfo4.Position(1)
        self.paneInfo4.Row(1)
        self.paneInfo4.CaptionVisible(showcaption)
        self.paneInfo4.BestSize([700, 400])

        self.mgr.AddPane(self._create_pane1(), self.paneInfo2)
        self.mgr.AddPane(self.renwini1, self.paneInfo3)
        self.mgr.AddPane(self.renwini3, self.paneInfo1)        
        self.mgr.AddPane(self.renwini2, self.paneInfo4)    
        self.AddSequencePlotter()       

        
    def _create_pane1(self):
        # instantiate the wxGlade-created frame
        ipf = GUI_wxglade.MyFrame(None, -1, "")
        # reparent the panel to us
        editorpanel = ipf.panel_1
        editorpanel.Reparent(self)
        
        editorpanel.bitmap_button_1 = ipf.bitmap_button_1
        editorpanel.bitmap_button_1_copy = ipf.bitmap_button_1_copy
        editorpanel.bitmap_button_3 = ipf.bitmap_button_3
        editorpanel.bitmap_button_4 = ipf.bitmap_button_4
        editorpanel.button_3 = ipf.button_3
        editorpanel.button_3_copy = ipf.button_3_copy
        
        editorpanel.button_1 = ipf.button_1
        editorpanel.button_2 = ipf.button_2
        editorpanel.button_4 = ipf.button_4
        
        editorpanel.radio_btn_1 = ipf.radio_btn_1
        editorpanel.radio_btn_2 = ipf.radio_btn_2
        editorpanel.radio_btn_3 = ipf.radio_btn_3
        editorpanel.radio_btn_4 = ipf.radio_btn_4
        editorpanel.radio_btn_5 = ipf.radio_btn_5
        
        editorpanel.checkbox_6 = ipf.checkbox_6
        editorpanel.checkbox_7 = ipf.checkbox_7
        editorpanel.checkbox_8 = ipf.checkbox_8
        
        editorpanel.tracercheckbox_1 = ipf.tracercheckbox_1
        editorpanel.tracercheckbox_2 = ipf.tracercheckbox_2
        editorpanel.tracercheckbox_3 = ipf.tracercheckbox_3
        editorpanel.tracercheckbox_4 = ipf.tracercheckbox_4
        editorpanel.tracercheckbox_5 = ipf.tracercheckbox_5
        
        editorpanel.spin_ctrl_1 = ipf.spin_ctrl_1
        editorpanel.spin_ctrl_2 = ipf.spin_ctrl_2
        editorpanel.slider_1 = ipf.slider_1
        editorpanel.slider_2 = ipf.slider_2
        
        editorpanel.radio_btn_6 = ipf.radio_btn_6
        editorpanel.radio_btn_7 = ipf.radio_btn_7
        

        ipf.Destroy()
        self.editorpanel = editorpanel
        return self.editorpanel
        
    def BindEvents(self):
        self.editorpanel.bitmap_button_1.Bind(wx.EVT_BUTTON, self.OnSave1)
        self.editorpanel.bitmap_button_1_copy.Bind(wx.EVT_BUTTON, self.OnSave2)        
        self.editorpanel.button_3.Bind(wx.EVT_BUTTON, self.OnLoad1)
        self.editorpanel.button_3_copy.Bind(wx.EVT_BUTTON, self.OnLoad2)
        self.editorpanel.bitmap_button_3.Bind(wx.EVT_BUTTON, self.OnHideBlue)
        self.editorpanel.bitmap_button_4.Bind(wx.EVT_BUTTON, self.OnHideYellow)
        self.editorpanel.button_1.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters)
        self.editorpanel.button_2.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters)
        self.editorpanel.button_4.Bind(wx.EVT_TOGGLEBUTTON, self.OnChangeFilters)
        self.editorpanel.checkbox_6.Bind(wx.EVT_CHECKBOX, self.OnShowBones)
        self.editorpanel.checkbox_7.Bind(wx.EVT_CHECKBOX, self.OnShowBonesXRAY) 
        self.editorpanel.checkbox_8.Bind(wx.EVT_CHECKBOX, self.OnShowExorotation)       
        self.editorpanel.radio_btn_1.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses)
        self.editorpanel.radio_btn_2.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses)
        self.editorpanel.radio_btn_3.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses)
        self.editorpanel.radio_btn_4.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses)
        self.editorpanel.radio_btn_5.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePoses)        
        self.editorpanel.slider_1.Bind(wx.EVT_SLIDER, self.OnSlider)
        self.editorpanel.slider_2.Bind(wx.EVT_SLIDER, self.OnSlider)
        self.editorpanel.tracercheckbox_1.Bind(wx.EVT_CHECKBOX, self.OnShowTracers)
        self.editorpanel.radio_btn_6.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePCP)
        self.editorpanel.radio_btn_7.Bind(wx.EVT_RADIOBUTTON, self.RegeneratePCP)
        
    def _init_menubar(self):
        self.menu1 = wx.Menu()
        self.menu2 = wx.Menu()
        self.menu3 = wx.Menu()
        self.menuBar1 = wx.MenuBar()
        
        self.menu1.Append(help='Save blue collection',
              id=wxID_SAVE, kind=wx.ITEM_NORMAL,
              text='Save blue collection')
        self.Bind(wx.EVT_MENU, self.OnSave1, id=wxID_SAVE)      
        tmpid = wx.NewId()
        self.menu1.Append(help='Save yellow collection',
              id=tmpid, kind=wx.ITEM_NORMAL,
              text='Save yellow collection')
        self.Bind(wx.EVT_MENU, self.OnSave2, id=tmpid)
        self.menu1.Append(help='Quit Application',
              id=wxID_QUIT, kind=wx.ITEM_NORMAL, text='Quit')
        self.Bind(wx.EVT_MENU, self.OnQuit, id=wxID_QUIT)
        
        tmp_id = wx.NewId()
        self.menu2.Append(help='Screenshot 1',
              id=tmp_id, kind=wx.ITEM_NORMAL,
              text='Screenshot 1')
        self.Bind(wx.EVT_MENU, self.StoreImage, id=tmp_id)    

        self.menuBar1.Append(menu=self.menu1, title='File')
        self.menuBar1.Append(menu=self.menu2, title='Edit')
        self.menuBar1.Append(menu=self.menu3, title='Help')
        
        return self.menuBar1
   
   
    def __init__(self, parent, root):
        self.parent = parent
        self._root = root
        self.timerCBcount = 0
        self.appdir = self.ReadRootDirectory()
        self.timerbugged = False
        self.sequenceplotters = []
        self.sequenceplotters_selectionboxes = []
        self.sequenceplotcount = 0
        self.scatterplotlist = []
        self.imagenumber = 0        
        self.posesOn = True
        self.tracersOn = True
                
        
        self._init_ctrls()
        self.fillScene()  
        self.widgets = WidgetCollection.create(self)
        self.tracer = TimeWindowTrace.create(self, self.renwini2, self.ren2)
        
        menuBar1 = self._init_menubar()
        self.SetMenuBar(menuBar1)
        
        self.BindEvents()
            
        self.Layout()
        self.Show()
        
    #~ def _init_coll_notebook2_Pages(self, parent):
        #~ parent.AddPage(imageId=-1, page=self.panel_1, select=True,
              #~ text='Default')
        #~ parent.AddPage(imageId=-1, page=self.measurepanel, select=True,
              #~ text='Measure Tools')
              
    def flip_y(self, y):
        return (self.renwini1.GetSize()[1] - y - 1)


    def StoreImage(self, whichone=1, high_res=1):

        newren = vtk.vtkRenderWindow()
        newren.OffScreenRenderingOn()
        newren.SetSize(2340, 1800)
        newren.AddRenderer(self.ren2)
        newren.Render()

        w2i = vtk.vtkWindowToImageFilter()
        w2i.SetInput(newren)
        w2i.SetMagnification(1)
        w2i.Update()
        pngWriter = vtk.vtkPNGWriter()
        pngWriter.SetInput(w2i.GetOutput())
        #w2i.Modified()
        self.imagenumber = self.imagenumber+1
        pngWriter.SetFileName('Screenshots/image%04d.png' % self.imagenumber)
        pngWriter.Write()
        
        newren.RemoveRenderer(self.ren2)

        
    def AddSequencePlotter(self):           
        dispsize = wx.DisplaySize()           
        paneInfoTime = wx.aui.AuiPaneInfo()        
        paneInfoTime.Bottom().Layer(0) #1
        paneInfoTime.Row(199 - self.sequenceplotcount)
        paneInfoTime.BestSize([dispsize[0] - 200, 50])
        paneInfoTime.MinSize([200, 50])
        paneInfoTime.CaptionVisible(False)
        self.sequenceplotcount = self.sequenceplotcount+1
        
        sequenceplotter = Plotter.create(self, self._root)             
        self.mgr.AddPane(sequenceplotter.iren, paneInfoTime)        
        self.mgr.Update()
        self.sequenceplotters.append(sequenceplotter)              
        sequenceplotter.ShowPlot()
        
    def AddScatter(self, plot1, plot2):
        stanceID1 = self.parent.Filters.plottedAngles[plot1]
        stanceID2 = self.parent.Filters.plottedAngles[plot2]        
        
        xyValues1 = []
        for i in range(0, len(self.parent.splineCollection)):
            if self.parent.Filters.FilterSingleSpline_WithoutVisualisation(\
                                                        self.parent.splineCollection[i], 0, i):
                xyValues1.append([self.parent.splineCollection[i]['stance'][stanceID1],
                                        self.parent.splineCollection[i]['stance'][stanceID2]])
        xLabel1 = self.parent.Filters.jointAngleCollection[stanceID1]['description']        
        yLabel1 = self.parent.Filters.jointAngleCollection[stanceID2]['description']
        xLabel1 = xLabel1.replace('\n', ' ')
        yLabel1 = yLabel1.replace('\n', ' ')
        
        xyValues2 = []
        for i in range(0, len(self.parent.splineReferences)):
            if self.parent.Filters.FilterSingleSpline_WithoutVisualisation(\
                                                        self.parent.splineReferences[i], 1, i):
                xyValues2.append([self.parent.splineReferences[i]['stance'][stanceID1],
                                        self.parent.splineReferences[i]['stance'][stanceID2]])
        xLabel2 = self.parent.Filters.jointAngleCollection[stanceID1]['description']        
        yLabel2 = self.parent.Filters.jointAngleCollection[stanceID2]['description']
        xLabel2 = xLabel2.replace('\n', ' ')
        yLabel2 = yLabel2.replace('\n', ' ')
        
        data1 = xyValues1, xLabel1, yLabel1
        data2 = xyValues2, xLabel2, yLabel2
        scatter = Scatter.Scatter(self, data1, data2, stanceID1, stanceID2)
        self.scatterplotlist.append(scatter)
        
    def RemoveSequencePlotter(self, id):  
        
        self.mgr.DetachPane(self.sequenceplotters[id].iren)
        self.sequenceplotters.pop(id)
        self.parent.Filters.RestartFiltering()
        self.parent.Filters.RestartFilteringReferences()

    def ReadRootDirectory(self):
        if hasattr(sys, 'frozen') and sys.frozen:
            appdir, exe = os.path.split(sys.executable)
        else:
            dirname = os.path.dirname(sys.argv[0])
            if dirname and dirname != os.curdir:
                appdir = dirname
            else:
                appdir = os.getcwd()
        return appdir
        
    def fillScene(self):        
        reader = vtk.vtkSTLReader()
        fname = os.path.join(self.appdir, 'torso.stl')
        reader.SetFileName(fname)
        output = reader.GetOutput()
        Normals = vtk.vtkPolyDataNormals()
        Normals.SetInput(output)#.GetOutput())
        Normals.SplittingOff()
        Normals.ConsistencyOff()
        TriangleFilter = vtk.vtkTriangleFilter()
        TriangleFilter.SetInput(Normals.GetOutput())
        TriangleFilter.Update()
        torsimapper = vtk.vtkPolyDataMapper()
        torsimapper.SetInput(TriangleFilter.GetOutput())
        self.torsiactor = vtk.vtkActor()
        self.torsiactor.SetMapper(torsimapper)
        self.torsiactor.GetProperty().SetAmbientColor(1.0, 1.0, 1.0)
        self.torsiactor.GetProperty().SetAmbient(1.0)
        self.ren1.AddActor(self.torsiactor)

    def UpdateRenderer2(self, event, bla):
        a = self.ren2.GetActiveCamera().GetViewTransformMatrix()
        campos = self.ren2.GetActiveCamera().GetPosition()
        self.parent.blue_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2])
        self.parent.blue_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0))
        self.parent.blue_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1))
        self.parent.blue_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2))
        self.parent.blue_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3))
        self.parent.yellow_shader.AddShaderVariableFloat ("camPos", campos[0], campos[1], campos[2])
        self.parent.yellow_shader.AddShaderVariableFloat ("camproj1", a.GetElement(0,0), a.GetElement(1,0), a.GetElement(2,0), a.GetElement(3,0))
        self.parent.yellow_shader.AddShaderVariableFloat ("camproj2", a.GetElement(0,1), a.GetElement(1,1), a.GetElement(2,1), a.GetElement(3,1))
        self.parent.yellow_shader.AddShaderVariableFloat ("camproj3", a.GetElement(0,2), a.GetElement(1,2), a.GetElement(2,2), a.GetElement(3,2))
        self.parent.yellow_shader.AddShaderVariableFloat ("camproj4", a.GetElement(0,3), a.GetElement(1,3), a.GetElement(2,3), a.GetElement(3,3))
        
    def UpdateRenderer3(self, event, bla):
        self.ren3overlay.RefreshOverlay()
        
    def RegeneratePCP(self, event):
        self.parent.RegenerateSplineObjects()
        
    def RegeneratePoses(self, event):
        if self.editorpanel.radio_btn_5.GetValue() == True:
            sj = -1
        elif self.editorpanel.radio_btn_1.GetValue() == True:
            sj = 0
        elif self.editorpanel.radio_btn_2.GetValue() == True:
            sj = 1
        elif self.editorpanel.radio_btn_3.GetValue() == True:
            sj = 2
        elif self.editorpanel.radio_btn_4.GetValue() == True:
            sj = 3
        #~ try:
        self.parent.stablejointindex = sj #0 = spine only, 1 = spine and clavicle etc.
        self.parent.RegeneratePoses()
        self.parent.Filters.RestartFiltering()
        self.parent.Filters.RestartFilteringReferences()
        #~ try:
            #~ self.Render()
        #~ except RuntimeError:
            #~ pass
        #~ except AttributeError:
            #~ print "Parent probably not linked. E31082009 A"
            
    def OnHideBlue(self, event):
        if self.parent.Filters.sessionvisible_A == True:
            fname = os.path.join(self.appdir, 'data_gray.jpg')
            self.editorpanel.bitmap_button_3.SetBitmapLabel(wx.Bitmap(fname))
            self.editorpanel.button_3.Enabled = False
            self.parent.Filters.sessionvisible_A = False            
        else:
            fname = os.path.join(self.appdir, 'data_blue.jpg')
            self.editorpanel.bitmap_button_3.SetBitmapLabel(wx.Bitmap(fname))
            self.editorpanel.button_3.Enabled = True
            self.parent.Filters.sessionvisible_A = True
        self.parent.Filters.RestartFiltering()
    
    def OnHideYellow(self, event):
        if self.parent.Filters.sessionvisible_B == True:
            fname = os.path.join(self.appdir, 'data_gray.jpg')
            self.editorpanel.bitmap_button_4.SetBitmapLabel(wx.Bitmap(fname))
            self.editorpanel.button_3_copy.Enabled = False
            self.parent.Filters.sessionvisible_B = False
        else:
            fname = os.path.join(self.appdir, 'data_yellow.jpg')
            self.editorpanel.bitmap_button_4.SetBitmapLabel(wx.Bitmap(fname))
            self.editorpanel.button_3_copy.Enabled = True
            self.parent.Filters.sessionvisible_B = True
        self.parent.Filters.RestartFilteringReferences()
        
    def SetSliders(self, stance):
        if self.showsliders:
            for i in range(0,15):
                self.sliderlist[i].SetValue(stance[i])
            
    def CustomPose(self, event):
        stance = []
        if self.showsliders:
            for i in range(0,15):
                stance.append(self.sliderlist[i].GetValue())
        try:
            act = self.parent.GeneratePhysique(stance, showbones = True)
            self.parent.pointWidget.SetPosition(self.parent.parent.blPos[13])
            try:
                self.ren2.RemoveActor(self.parent.PoseActor9)
            except AttributeError:
                pass
            self.parent.PoseActor9.SetMapper(act.GetMapper())
            self.ren2.AddActor(self.parent.PoseActor9)
        except AttributeError:
            print "Parent probably not linked. E31082009 B"
        
        self.Render(2)
        
                
    def Render(self, whichone = 0):
        if whichone == 0 or whichone == 1:
            self.renwini1.Render()
        if whichone == 0 or whichone == 2:
            self.renwini2.Render()
        if whichone == 0 or whichone == 3:
            self.renwini3.Render()
        
    def OnSave1(self, event):
        filename = self.parent.ExportSplines(0)
        self.editorpanel.button_3.SetLabel(filename)
        
    def OnSave2(self, event):
        filename = self.parent.ExportSplines(1)
        self.editorpanel.button_3_copy.SetLabel(filename)
        
    def OnQuit(self, event):
        self.parent.quit()
        
    def OnMean(self, event):
        self.parent.MedianMeanSpline(True)
    
    def OnMedian(self, event):
        self.parent.MedianMeanSpline(False)
        
    def OnShowBones(self, event):
        for bone in self.parent.bone_actorList:
            bone.SetVisibility(self.editorpanel.checkbox_6.GetValue())
        self.Render(2)
        
    def OnShowBonesXRAY(self, event):
        if self.editorpanel.checkbox_7.GetValue():
            for i in range(0, len(self.parent.bone_actorList)):
                self.parent.bone_actorList[i].SetMapper(self.parent.bone_mapperList[i])
                self.parent.bone_actorList[i].SetProperty(self.parent.xray_shader)
        else:
            for i in range(0, len(self.parent.bone_actorList)):
                self.parent.bone_actorList[i].SetMapper(self.parent.bone_mapperListNormal[i])
                self.parent.bone_actorList[i].SetProperty(vtk.vtkProperty())
                self.parent.bone_actorList[i].GetProperty().SetColor(1, .97, .85)
        
        
    def OnShowExorotation(self, event):
        value = self.editorpanel.checkbox_8.GetValue() * 1.0
        self.parent.exoblue_shader.AddShaderVariableFloat("Amplitude", value)
        self.parent.exoyellow_shader.AddShaderVariableFloat("Amplitude", value)
        self.AddScatter()
        
    def OnResetBones(self, event):
        self.SetSliders([0 for x in range(15)])
        self.CustomPose(None)
        self.widgets.UpdateWidgets()
        
    def OnChangeFilters(self, event):
        self.parent.Filters.widgetFiltersOn = self.editorpanel.button_1.GetValue()
        self.parent.Filters.sequenceFilterOn = self.editorpanel.button_4.GetValue()
        if self.editorpanel.button_2.GetValue():
            self.parent.pointWidget.SetEnabled(1)
            self.parent.pointWidget.SetPosition(self.parent.parent.blPos[13]) 
            self.parent.ProbeData(event, None)
        else:
            self.parent.pointWidget.SetEnabled(0)
            self.parent.Filters.inversekinematicsOn = False
        
        self.parent.Filters.RestartFiltering()
        self.parent.Filters.RestartFilteringReferences()
        

 

    def OnLoad1(self, event):        
        dlg = wx.FileDialog(self, message="Load motion collection", defaultDir=os.getcwd(), defaultFile="",
        wildcard="FoB file (*.txt)|*.txt", style=wx.OPEN | wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()            
            self.LoadFile1(filename)
        dlg.Destroy()
        
    def OnSlider(self, event):
        self.parent.Filters.UpdateShaderOpacity()        
        
    def LoadFile1(self, path):
        self.parent.ClearData(0)
        importfile = open(path, 'r', 1)
        lines = importfile.readlines()
        for i in range (0, len (lines)/2):
            stance = eval(lines[i*2])
            blPos = eval(lines[i*2+1])
            self.parent.AddSpline(stance, blPos, updatewidget = False, referenceSpline = False)
        importfile.close()

        splitpath = os.path.split(path)        
        self.editorpanel.button_3.SetLabel(splitpath[len(splitpath)-1])
        self.widgets.UpdateWidgets()
        
    def OnLoad2(self, event):        
        dlg = wx.FileDialog(self, message="Load motion collection", defaultDir=os.getcwd(), defaultFile="",
        wildcard="FoB file (*.txt)|*.txt", style=wx.OPEN | wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()
            self.LoadFile2(filename)
        dlg.Destroy()
        
    def LoadFile2(self, path):
        self.parent.ClearData(1)
        importfile = open(path, 'r', 1)
        lines = importfile.readlines()
        for i in range (0, len (lines)/2):
            stance = eval(lines[i*2])
            stance[6] = stance[6] + 13
            stance[8] = stance[8] + 10
            stance[9] = stance[9] - 7
            blPos = eval(lines[i*2+1])
            self.parent.AddSpline(stance, blPos, updatewidget = False, referenceSpline = True)
        importfile.close()
        
        splitpath = os.path.split(path)        
        self.editorpanel.button_3_copy.SetLabel(splitpath[len(splitpath)-1])
        self.widgets.UpdateWidgets()
        
    def JointClicked(self, event):# calledBy, event):        
        x,y = event.GetX(), event.GetY()
        vtk_y = self.flip_y(y)

        self.cellpicker.Pick(x, vtk_y, 0, self.ren1overlay.renXannotation)
        if self.cellpicker.GetPointId() < 0:
            self.renwini1.OnButtonDown(event)
        else:
            act = self.cellpicker.GetActor()
            
            #if act!=None:
            if act in [self.ren1overlay.spineact,\
                          self.ren1overlay.clavact,\
                          self.ren1overlay.scapact,\
                          self.ren1overlay.GHact,\
                          self.ren1overlay.ELact]:
                self.ren1overlay.ShowMenu(act)
            else:
                self.renwini1.OnButtonDown(event)

    def UpdateSequencePlot(self, stanceIndex, whichplot=0, whichdata=0):
        label = self.parent.Filters.jointAngleCollection[stanceIndex]['description']
        label = label.replace('\n', ' ')
        if whichdata==0:
            self.sequenceplotters[whichplot].plotcolor = (0.7, 0.7, 1.0)
        else:
            self.sequenceplotters[whichplot].plotcolor = (1.0, 1.0, 0.7)
        self.sequenceplotters[whichplot].label = label
        self.sequenceplotters[whichplot].yValues1 = []
        self.sequenceplotters[whichplot].whichdata = whichdata
        if whichdata==0:
            for i in range(0, len(self.parent.splineCollection)):            
                self.sequenceplotters[whichplot].yValues1.append(self.parent.splineCollection[i]['stance'][stanceIndex]/90.0)
        else:
            for i in range(0, len(self.parent.splineReferences)):            
                self.sequenceplotters[whichplot].yValues1.append(self.parent.splineReferences[i]['stance'][stanceIndex]/90.0)
        
        #~ print self.sequenceplotters[whichplot].yValues1
        self.sequenceplotters[whichplot].CreatePlot()
        self.sequenceplotters[whichplot].ShowPlot()
        self.sequenceplotters[whichplot].iren.Render()
        
    def UpdateSequencePlotOverlays(self):
        for sequenceplotter in self.sequenceplotters:
            sequenceplotter.ShowOverlay()
            
    def OnShowTracers(self, event):
        if self.editorpanel.tracercheckbox_1.GetValue()==False:
            self.tracer.ClearTraces(0)
            self.tracer.ClearTraces(1)
            self.Render()

        
    def timerCB(self, calledBy, event):        
        if not self.timerbugged:
            self.timerCBcount = self.timerCBcount + 1
            try:
                self.parent.PlayShader()
                if self.parent.Filters.initiateFilterTimer == False:
                    self.parent.Filters.FilterAllStepper()
                if self.parent.Filters.initiateFilterReferencesTimer == False:
                    self.parent.Filters.FilterAllReferenceStepper()
                try:
                    self.Render(2)
                    self.Render(3)
                except RuntimeError:
                    pass
                
                if self.timerCBcount%10 ==0:
                    for scatterplot in self.scatterplotlist:
                        scatterplot.UpdatePlot()
                
                
            except AttributeError:
                self.timerbugged = True
                print "Timed events not working. The parent is probably not linked. E13102009"
        else:
            time.sleep(1)

class MyApp(wx.App):
    def OnInit(self):
        frame = wxFrame(None, None)     
        #~ frame.sequenceplotter.yValues1 = [0.3, 0.1, 0.4, 0.5, 0.9]
        #~ frame.sequenceplotter.label = "Hello there!"
        #~ frame.sequenceplotter.CreatePlot()
        #~ frame.sequenceplotter.ShowPlot()
        frame.Show()
        self.SetTopWindow(frame)
        return 1

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()